package com.liyuci.core.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.liyuci.core.exception.ErrorCode;

import java.io.Serializable;

import org.apache.commons.lang3.StringUtils;

/**
 * RestController方法通用的返回类型
 * @author liyuci
 * @date 2018-02-07 21:00:25
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RestResult implements Serializable {

	private static final long serialVersionUID = 1L;
	/**
     * 返回编码
     */
	@JSONField(ordinal = 1)
    private int code;

    /**
     * 返回消息
     */
	@JSONField(ordinal = 2)
    private String message;

    /**
     * 返回数据
     */
	@JSONField(ordinal = 3, serialzeFeatures = SerializerFeature.WriteMapNullValue)
    private Object data;
	
    public RestResult() {
    	throw new UnsupportedOperationException();
    }
    
    public RestResult(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public RestResult(int code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
    
	public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return StringUtils.trimToEmpty(message);
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
    
    public static RestResult ok() {
        return new RestResult(ErrorCode.OK.getCode(), ErrorCode.OK.getMessage());
    }
    
    public static RestResult failure() {
        return new RestResult(ErrorCode.FAILURE.getCode(), ErrorCode.FAILURE.getMessage());
    }
    
    public static RestResult ok(Object data) {
    	return new RestResult(ErrorCode.OK.getCode(), ErrorCode.OK.getMessage(), data);
    }
    
    public static RestResult failure(ErrorCode errorCode) {
        return new RestResult(errorCode.getCode(), errorCode.getMessage());
    }
    
    @Override
    public String toString() {
        return "RestResult(code=" + this.code + ", message=" + this
                .message + ", data=" + JSON.toJSONString(this.data) + ")";
    }
}
